from app.models.category_model import Sample, AlCategory
from config import ALIYUN_ACCESS_KEY_ID, ALIYUN_ACCESS_KEY_SECRET,WORKSPACE_ID
from sqlalchemy.orm import Session
from app.database.db_setup import get_db


def add_category(
    category_name: str ,
    category_type: str='UNSTRUCTURED' 
):
    try:
        if not ALIYUN_ACCESS_KEY_ID or not ALIYUN_ACCESS_KEY_SECRET or not WORKSPACE_ID:
            return {"error": "请设置 ALIYUN_ACCESS_KEY_ID 和 ALIYUN_ACCESS_KEY_SECRET和WORKSPACE_ID 环境变量"}
        result = Sample.call_add_category(
            ALIYUN_ACCESS_KEY_ID,
            ALIYUN_ACCESS_KEY_SECRET,
            WORKSPACE_ID,
            category_name,
            category_type,
        )
        return result
    except FileNotFoundError:
        return {"error": f"文件 {file_name} 未找到"}
    except Exception as e:
        return {"error": str(e)}


def create_category(
    script_id:int,
    name: str,
    CategoryId: str,
    add_time: int,
    db: Session
):
    new_category = AlCategory(
        script_id=script_id,
        name=name,
        CategoryId=CategoryId,
        add_time=add_time
    )
    try:
        db.add(new_category)
        db.commit()
        db.refresh(new_category)
        return new_category
    except Exception as e:
        db.rollback()
        raise e
